package com.huazai.thread;

import java.util.Scanner;

public class Main {
	public static void main(String[] args) throws InterruptedException {
		Scanner sc = new Scanner(System.in);
		// System.out.println("请输入票数：");
		int num = sc.nextInt(); // 从键盘读入总票数
		Ticket tickets = new Ticket(num); // 产生票

		new Thread(new sellTicketThread(tickets)).start();// sellTicketThread售票
		new Thread(new returnTicketThread(tickets)).start();// returnTicketThread退票

		Thread.sleep(50); // 休眠等待售票和退票执行完毕
		System.out.println(tickets.freeNum);
	}
}

class Ticket {
	int total; // 总票数
	int freeNum; // 多线程共享变量：余票数量
	int soldNum; // 已售出票数
	boolean hasTicket; // true表示有足够的票出售，false则表示票数不够

	int count = 3; // 线程售票退票次数
	int sellNum = 3; // 单次售票数量
	int returnNum = 2; // 单次退票数量

	public Ticket(int number) {
		total = number;
		freeNum = total; // 售票前：总数与余票数相等
		soldNum = 0; // 已售出票数
		hasTicket = (freeNum >= sellNum); // 余票足够
	}

	synchronized public void sellTicket(int num) {//num表示购票数
		while(true) {
			if(count==0) {
				//售票次数用完了
				break;
			}else {
				//售票次数没有用完
				//判断有没有余票
				if(freeNum>=sellNum) {
					//余票足够，进行售票
					freeNum-=num;
					soldNum+=num;
					count--;
					System.out.println("售出"+num+"余票"+freeNum);
					//唤醒退票线程
					this.notify();
				}else{
					//余票不够 等待退票
					try {
						this.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	synchronized public void returnTicket(int num) {//num表示退票数
		while(true) {
			if(count==0) {
				//退票次数已经用完
				break;
			}else {
				//退票次数没有用完
				//有票售出才能开始退票
				if(soldNum==0) {
					//没有票被售出 等待
					try {
						this.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}else {
					//有票被售出
					if(num>soldNum) {
						//退回实际数量的票
						int temp=soldNum;
						freeNum+=soldNum;
						soldNum=0;
						count--;
						System.out.println("退回"+temp+"余票"+freeNum);
						//唤醒
						this.notify();
					}else {
						//就退num
						freeNum+=soldNum;
						soldNum-=num;
						count--;
						System.out.println("退回"+num+"余票"+freeNum);
						//唤醒
						this.notify();
					}
				}
			}
		}
	}
}
